<template>
    <el-form :model="addBanner" label-width="120px">
        <el-form-item label="图片地址">
            <el-input v-model="addBanner.img" placeholder="图片的http地址(必选)" />
        </el-form-item>
        <el-form-item label="图片链接">
            <el-input v-model="addBanner.link" placeholder="图片的连接(可选)" />
        </el-form-item>
        <el-form-item label="图片提示">
            <el-input v-model="addBanner.alt" placeholder="图片描述(可选)" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">添加</el-button>
            <el-button @click="clearData">取消</el-button>
        </el-form-item>
    </el-form>
</template>
  
<script lang="ts" setup>
import type { AxiosResponse } from 'axios';
import { reactive } from 'vue'
import service from '../../../utils/service';
import { ElMessage } from 'element-plus'
// do not use same name with ref
interface IAddBanner {
    img: string,
    alt: string,
    link: string
}

const addBanner = reactive<IAddBanner>({
    img: "",
    alt: "",
    link: ""
})
// 点击取消清除输入框数据
const clearData = () => {
    let key: keyof IAddBanner
    for (key in addBanner) {
        addBanner[key] = ""
    }
}
const addBannerData = () => {
    service({
        url: `/banner/add`,
        method: "post",
        data: addBanner
    }).then((res: AxiosResponse) => {
        if (res.data.code === "200") {
            console.log("add success");
            ElMessage({
                showClose: true,
                message: "数据添加成功",
                type: "success"
            })
            clearData()
        }

    })
}

const onSubmit = () => {
    if (addBanner.img) {
        addBannerData()
    } else {
        ElMessage({
            showClose: true,
            message: "请至少输入图片链接！",
            type: "warning"
        })
    }
}
document.onkeydown = (evt) => {
    let e = evt
    let key = e.code
    if (key == "Enter") {
        if (addBanner.img) {
            addBannerData()
        } else {
            ElMessage({
                showClose: true,
                message: "请至少输入图片链接！",
                type: "warning"
            })
        }
    }

}
</script>
  



<style scoped></style>